<template>
  <el-container>
    <el-aside>
      <el-container>
        <el-row type="flex" align="middle" style="height: 60px;padding-right: 10px;">
          <el-col :span="5" style="padding: 10px">
            <div :style="{ height: '35px', width: '35px', backgroundColor: form.backColor, borderRadius: '50%', overflow: 'hidden', display: 'flex', justifyContent: 'center', alignItems: 'center' }">
              <el-icon style="font-size:16px;cursor: pointer;" :style="{'background-color': form.backColor, 'color': form.iconColor}"><component :is="form.appIcon" /></el-icon>
            </div>
          </el-col>
          <el-col :span="13" style="font-size: 15px; font-weight: bolder;">
            {{ form.appName }}
          </el-col>
          <el-col :span="6" style="text-align: right;">
            <!-- <i class="jd-icon icon-import" style="font-size: 20px; color: #5d5d5d; cursor: pointer; margin-right: 5px;"></i>
            <i class="jd-icon icon-export" style="font-size: 20px; color: #5d5d5d; cursor: pointer; margin-right: 5px;"></i> -->
            <i class="jd-icon icon-setting" style="font-size: 20px; color: #5d5d5d; cursor: pointer;" @click="addAppUser"></i>
          </el-col>
        </el-row>
        <el-divider style="padding: 0px; margin: 0px" />
        <el-main class="nopadding" style="background-color: transparent">
          <el-row v-if="!form.isMenu">
            <el-col>
              <el-empty description="请先开启应用菜单" :image-size="100" style="margin-top: 200px"></el-empty>
            </el-col>
          </el-row>
          <!-- <menuTree v-else v-model="form.menuList"></menuTree> -->
          <menuTree v-else :modelValue="form.menuList" @update:modelValue="getAppMenu"></menuTree>
        </el-main>
        <el-footer style="text-align: center; height: auto; padding-top: 9px; padding-bottom: 9px">
          <el-button-group>
            <el-button :type="form.isMenu ? 'danger' : 'info'" @click="onOffAppMenu">
              <span v-if="!form.isMenu">开启应用菜单</span>
              <span v-else>关闭应用菜单</span>
            </el-button>
            <el-button :type="form.isMenu ? 'primary' : 'info'" @click="openMenuAuthDialog">设置菜单权限</el-button>
          </el-button-group>
        </el-footer>
      </el-container>
    </el-aside>
    <el-container>
      <el-main style="padding: 30px">
        <el-row style="width: 500px; margin: 0px auto; font-size: 20px; font-weight: bolder; text-align: center; height: 120px; line-height: 120px">
          <el-col :span="8">
            <span style="border-bottom: solid 3px #409eff; padding-bottom: 10px; cursor: pointer">应用设计</span>
          </el-col>
          <el-col :span="8">
            <span style="cursor: pointer" @click="createPage('/app/model')">数据模型</span>
          </el-col>
          <el-col :span="8">
            <span style="cursor: pointer" @click="createPage('/app/interface')">数据接口</span>
          </el-col>
        </el-row>
        <el-row style="font-size: 18px; font-weight: bolder; height: 60px; line-height: 60px; padding-left: 20px"> 创建以下页面，开始构建应用 </el-row>
        <el-row type="flex" align="middle" style="margin: 0 10px; padding-top: 15px" :gutter="20">
          <el-col :lg="12" :xl="8" v-for="item in pageType" :key="item">
            <el-card class="appbox-card" shadow="always">
              <template #header>
                <div class="card-header">
                  <span>{{ item.label }}</span>
                  <el-button text icon="el-icon-plus" @click="createPage(item.pageUrl, item.target)" style="margin: 0px; padding: 0px" :disabled="item.isMenu && !form.isMenu">创建</el-button>
                </div>
              </template>
              <el-row type="flex" align="middle">
                <el-col :span="10">
                  <template v-if="item.isMenu && !form.isMenu">
                    <el-icon style="font-size: 55px; fill: rgba(255, 255, 255); background-color: #409eff" class="app-icon"><component :is="item.icon" /></el-icon>
                  </template>
                  <template v-else>
                    <el-icon style="font-size: 55px; fill: rgba(255, 255, 255); background-color: #409eff; cursor: pointer" class="app-icon" @click="createPage(item.pageUrl, item.target)"><component :is="item.icon" /></el-icon>
                  </template>
                </el-col>
                <el-col :span="14" class="app-name">
                  {{ item.desc }}
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>

        <el-row style="margin: 15px 10px 0" :gutter="20">
          <el-col :lg="24" :xl="18" v-if="isAdmin">
            <el-row style="font-size: 18px; font-weight: bolder; height: 60px; line-height: 60px"> 设置开发权限 </el-row>
            <el-row type="flex" style="padding-top: 15px" :gutter="20">
              <transition-group name="fade">
                <el-col :lg="12" :xl="8" v-for="developer in developerList" :key="developer.id">
                  <el-card class="role-card">
					          <el-tag style="float: right" type="danger" v-if="developer.devType == 1">所有者</el-tag>
                    <el-row type="flex" align="middle" class="developer-card">
                      <el-col :span="24" class="body__wrap">
                        <div>
                          <el-avatar @error="() => true" class="avatar__wrap" :src="developer.avatar">
                            <div class="defalut-img">
                              {{ developer.devName.slice(0, 1) }}
                            </div>
                          </el-avatar>
                        </div>
                        <div>
                          <div class="name">{{ developer.devName }}</div>
                          <div class="phone">{{ developer.devPhone }}</div>
                        </div>
                      </el-col>
                      <el-popconfirm style="margin-left: 20px" title="确定要移除吗？" v-if="developer.devType != 1" @confirm="delDeveloper(developer, $event)">
                        <template #reference>
                          <el-icon class="close-icon" style="font-size: 20px"><el-icon-close /></el-icon>
                        </template>
                      </el-popconfirm>
                    </el-row>
                  </el-card>
                </el-col>
              </transition-group>

              <el-col :xs="24" :sm="20" :md="16" :lg="12" :xl="8" v-if="developerList.length < 3">
                <el-card shadow="always" class="role-card">
                  <el-row type="flex" align="middle" class="developer-card">
                    <el-col :span="24" style="text-align: center">
                      <el-button text icon="el-icon-plus" @click="addDeveloper" style="margin: 0px; padding: 0px; font-size: 15px">添加开发者</el-button>
                    </el-col>
                  </el-row>
                </el-card>
              </el-col>
            </el-row>
          </el-col>
          <el-col :lg="12" :xl="6">
            <el-row style="font-size: 18px; font-weight: bolder; height: 60px; line-height: 60px; margin-bottom: 15px">设置应用角色 </el-row>
            <el-card class="set-role" shadow="always">
              <el-row type="flex" align="middle" @click.native="openRoleListDialog">
                <el-col :span="8">
                  <el-icon style="border-radius: 12px; width: 60px; height: 60px; font-size: 28px; fill: rgba(255, 255, 255); color: #fff; background-color: #409eff">
                    <el-icon-user-filled></el-icon-user-filled>
                  </el-icon>
                </el-col>
                <el-col :span="16">
                  <el-button class="set-role-btn" text icon="el-icon-edit" @click.stop="openRoleListDialog">应用角色管理</el-button>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
    <el-aside>
      <el-container>
        <el-header>
          <el-row>
			      <el-col :span="5" style="text-align: center; font-size: 14px">
              <DictTag :options="app_status" :value="punlicStatus"></DictTag>
            </el-col>
          </el-row>
          <el-row>
            <el-button type="primary" @click="updateAppInfo" v-if="punlicStatus == '1'" :loading="appSaveLoading">立即发布</el-button>
			      <el-button type="danger" @click="updateAppInfo" v-else :loading="appSaveLoading">应用下架</el-button>
          </el-row>
        </el-header>
        <el-main class="nopadding">
          <el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-position="top" label-width="100px" style="padding: 15px;">
            <el-form-item label="应用名称" prop="appName">
              <el-input v-model="form.appName" maxlength="50" placeholder="应用名称" />
            </el-form-item>
            <el-form-item label="应用包名" prop="appPackage">
              <el-input placeholder="com.jportal.app" v-model="form.appPackage" maxlength="50" disabled> </el-input>
            </el-form-item>
            <el-form-item label="归属部门" prop="deptId">
              <jd-cascader v-model="form.deptId" :apiObj="$API.system.dept.tree" :apiProps="{ label: 'label', value: 'id' }" style="width: 100%" placeholder="请选择..." disabled></jd-cascader>
            </el-form-item>
            <el-form-item label="应用职能" prop="appClassify">
              <jd-select v-model="form.appClassify" dict="sys_app_classification" dataType="String" filterable style="width: 100%" placeholder="请选择..."></jd-select>
            </el-form-item>
            <el-form-item label="应用分类" prop="appType">
              <jd-select v-model="form.appType" dict="sys_app_types" dataType="String" filterable style="width: 100%" placeholder="请选择..."></jd-select>
            </el-form-item>
            <el-form-item label="数据存储" prop="database">
              <jd-select v-model="form.database" :apiObj="$API.app.dbConn.getConnects" :apiProps="{ label: 'connName', value: 'connId' }" style="width: 100%" placeholder="请选择..." disabled></jd-select>
            </el-form-item>
            <el-form-item label="应用介绍" prop="appDescribe">
              <el-input v-model="form.describe" maxlength="500" type="textarea" rows="5" show-word-limit placeholder="应用的一句话介绍" />
            </el-form-item>
            <!-- <el-divider>
              <el-link icon="el-icon-arrow-down" :underline="false">
                <span style="padding-left: 5px">更多信息</span>
              </el-link>
            </el-divider> -->
          </el-form>
        </el-main>
        <!-- <el-footer style="font-size: 13px; line-height: 150%">
          <el-row> 应用版权：© 2023 计算机信息技术学院 </el-row>
          <el-row> 开发支持：{{ userInfo.nickName }} {{ userInfo.phonenumber }} </el-row>
        </el-footer> -->
      </el-container>
    </el-aside>
  </el-container>

  <!-- <create-dialog v-if="dialog.appCreate" @close="refresh" ref="createDialog"  @success="handleSaveSuccess" @closed="dialog.appCreate=false"></create-dialog> -->

  <developerAddDialog ref="developerAdd"></developerAddDialog>
  <menuAuthDialog ref="menuAuth"></menuAuthDialog>
  <roleListDialog ref="roleList"></roleListDialog>
  <userAddDialog ref="addUser"></userAddDialog>
</template>

<script>
import useTabs from "@/utils/useTabs"
//import createDialog from './create';
// import developerDialog from "./components/developer.vue"
import developerAddDialog from "./components/developer-add.vue"
import menuTree from "./components/menu-tree.vue"
import menuAuthDialog from "./components/menu-auth.vue"
import roleListDialog from "./components/role-list.vue"
import userAddDialog from "./components/user-add.vue"

export default {
  name: "appStore",
  components: {
    developerAddDialog,
    menuTree,
    menuAuthDialog,
    roleListDialog,
    userAddDialog
  },
  data() {
    return {
      appSaveLoading: false,
      userInfo: {},
      app_status: [],
      apiObj: this.$API.system.member.list,
      timer: "", //定义一个定时器
      nowTime: "",
      dialog: {
        appCreate: false
      },
      punlicStatus:'1',
      appId: 0,
	    isAdmin:false,
      form: {
        appId: 0,
        appCode: "",
        deptId: "",
        isMenu: false,
        appType: "",
        appName: "",
        menuList: []
      },
      pageType: [
        { label: "数据列表", icon: "jd-icon-build", isMenu: false, pageUrl: "/app/store/design/datacenter", desc: "以数据列表形式展示用户填报的数据" },
        { label: "表单页面", icon: "jd-icon-form", isMenu: false, pageUrl: "/app/store/design/form", target: "_blank", desc: "适用于数据查询、数据上报、数据收集" },
        { label: "审批流程", icon: "jd-icon-people", isMenu: false, pageUrl: "/app/store/design/workflow", target: "_blank", desc: "适用于业务流程审核，多人协同审批" },
        { label: "应用门户", icon: "jd-icon-dashboard", isMenu: true, pageUrl: "#", desc: "为当前应用构建一个工作台形式的首页面" },
        { label: "应用链接", icon: "jd-icon-international", isMenu: true, pageUrl: "#", target: "_blank", desc: "从应用中链接到外部系统或应用间互链" }
      ],
      developerList: []
    }
  },
  created() {
    this.appId = this.$route.query.appId
	  this.checkAdmin()
    this.loadAppInfo()
    this.getDict()
	  this.getDeveloperList();
    // 自动折叠菜单
    this.$store.commit('TOGGLE_IsCollapse', true);
  },
  methods: {
    // app发布状态字典
    async getDict() {
      this.app_status = await this.Dict.get("sys_app_status")
    },
	// 获取应用菜单
	async getAppMenu() {
		let res = await this.$API.app.menu.list.get(this.appId);
		if (res.code == 200){
			this.form.menuList = res.data;
		}
	},
    // 用于设置版权
    getUserInfo() {
      this.userInfo = this.$TOOL.data.get("USER_INFO").user
    },
    // 设置应用发布状态
    async updateAppInfo() {
      this.appSaveLoading = true;
      this.form.appStatus = this.punlicStatus == '1'?'0':'1';
      var res = {};
      if (this.punlicStatus == '1'){
        res = await this.$API.app.appStore.updateApp.put(this.form);
        if (res.code == 200){
          this.$message.success("操作成功");
          this.loadAppInfo();
        } else {
          this.$message.error("系统错误,请稍后再试");
        }
      } else {
        // 应用下架
        this.$confirm('此操作将从应用中心下架该应用，确认继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        .then(async () => {
          res = await this.$API.app.appStore.updateApp.put(this.form);
          if (res.code == 200){
            this.$message.success("操作成功");
            this.loadAppInfo();
          } else {
            this.$message.error("系统错误,请稍后再试");
          }
        })
      }
      this.appSaveLoading = false
    },
    // 创建应用页面
    createPage(pageUrl, target) {
      if (target == '_blank'){
        let routeData = this.$router.resolve({
          path: pageUrl,
          query: {
            appId: this.appId
          }
        })
        window.open(routeData.href, "_blank")
      } else {
        this.$router.push({
          path: pageUrl,
          query: {
            appId: this.appId
          }
        });
      }
    },
    // 预览应用
    preview() {
      let routeData = this.$router.resolve({
        path: "/app/store/preview",
        query: {
          appId: this.appId
        }
      })
      window.open(routeData.href, "_blank")
    },
    // 获取应用信息
    async loadAppInfo() {
      var res = await this.$API.app.appStore.getInfo.get(this.appId)
      if (res.code == 200) {
		this.form.isMenu=res.data.menuStatus == 0;
		this.getAppMenu();
		this.punlicStatus=res.data.appStatus
        Object.assign(this.form, res.data)
        // 设置页面标题
        useTabs.setTitle("应用设计 - " + this.form.appName)
      }
      this.getUserInfo()
    },
    // 开启关闭应用菜单
    onOffAppMenu() {
      if (this.form.isMenu) {
        this.$confirm(`您确认要关闭应用菜单吗？`, "提示", {
          type: "warning"
        })
          .then(async () => {
			  var res = await this.$API.app.appStore.updateAppMenu.put(this.appId)
			  if (res.code == 200){
				  this.form.isMenu = false
				  this.$message.success("操作成功")
			  }else {
				  this.$message.error("操作失败")
			  }
		  })
          .catch(() => {})
      } else {
		this.getAppMenu();
        this.form.isMenu = true
      }
    },
	// 刷新开发者
	refreshDevloper(){
		this.getDeveloperList();
	} ,
	// 校验是否应用管理员
	async checkAdmin() {
		let res = await this.$API.system.member.checkAdmin.get(this.appId);
		this.isAdmin = res.data > 0;
	},
    // 添加应用用户
    addAppUser() {
      this.$refs.addUser.open()
    },

    // 添加开发者
    addDeveloper() {
      this.$refs.developerAdd.open()
    },
	// 获取开发者列表
	async getDeveloperList() {
		let res = await this.$API.system.member.getDevList.get(this.appId);
		if (res.code == 200){
			this.developerList =res.data;
		}
	},
    // 删除开发者
    async delDeveloper(item) {
		let res = await this.$API.system.member.delDev.delete(item.id)
		if (res.code == 200){
			this.$message.success("移除成功");
			this.getDeveloperList();
		}else {
			this.$message.error("移除失败");
		}
	},
    // 打开应用菜单权限设置对话框
    openMenuAuthDialog() {
      if (!this.form.isMenu) {
        this.$message.warning("请先开启应用菜单")
        return
      }
      this.$nextTick(() => {
        this.$refs.menuAuth.open()
      })
    },
    // 打开设置操作角色页面对话框
    openRoleListDialog() {
      this.$nextTick(() => {
        this.$refs.roleList.open(this.appId);
      })
    }
  }
}
</script>
<style lang="scss">
.appbox-card {
  width: 100%;
  overflow: hidden;
  transition: transform 0.3s;

  &:hover {
    transform: translateY(-5px);
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .app-icon {
    width: 90px;
    height: 90px;
    padding: 15px;
    border-radius: 12px;
  }
  .app-name {
    font-size: 15px;
    line-height: 150%;
  }
}

.leftPanel {
  background: #fff;
  padding: 30px;
  padding-right: 15px;
  border: 0px;
  overflow: hidden;

  .searchBox {
    margin: 0px auto;
    width: 600px;
    margin-top: calc((100vh - 680px) / 2);
    margin-bottom: calc((100vh - 680px) / 2);

    .input {
      width: 550px;
      height: 45px;
      line-height: 45px;
      font-size: 16px;
      border: solid 2px #dcdfe6;
      border-radius: 6px;
      position: relative;

      .el-input-group__prepend,
      .el-input__wrapper {
        position: relative;
        box-shadow: none !important;
        width: 120px;

        .select {
          position: absolute;
          clip: rect(2px 120px 30px 2px);
          width: 120px;
          height: 30px;
          line-height: 30px;
          font-size: 15px;
          left: 10px;
          top: 3px;
          font-weight: bold;
        }
      }

      .el-input-group__append {
        background: #409eff;
        color: #fff;
        width: 90px;
      }
    }
  }

  .appbox-card {
    width: 100%;
    height: 500px;
    overflow: hidden;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .app-icon {
      width: 120px;
      fill: rgba(253, 253, 253, 0.65) !important;
      background-color: #409eff;
      padding: 30px;
      border-radius: 12px;
    }
    .app-name {
      text-align: center;
      margin-top: 10px;
      font-size: 14px;
    }
  }
}
.rightPanel {
  width: 360px;
  border: 0px !important;

  .nowTime {
    border: 0px;
    font-size: 18px;
    font-weight: bolder;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    justify-content: center;
    padding: 0px;
    height: 90px;
    padding-top: 20px;
  }

  .applog-card {
    width: 100%;
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .card-content {
      height: calc(100vh - 300px);
      overflow-y: auto;

      .item {
        font-size: 14px;
        margin-bottom: 18px;
      }
    }
  }
}

/* 1. 声明过渡效果 */
.fade-move,
.fade-enter-active,
.fade-leave-active {
  transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
}

/* 2. 声明进入和离开的状态 */
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: scale(0.01) translateY(30px);
}

/* 3. 确保离开的项目被移除出了布局流
      以便正确地计算移动时的动画效果。 */
.fade-leave-active {
  position: absolute;
}
.role-card {
  .el-card__body {
    padding: 15px;
  }
  .developer-card {
    justify-content: space-between;
    align-items: center;
    position: relative;
    box-sizing: border-box;
    cursor: pointer;
    height: 60px;
    .avatar__wrap {
      margin-right: 10px;
      width: 60px;
      height: 60px;
      flex-shrink: 0;
      .defalut-img {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #409eff;
        font-size: 28px;
        font-weight: bold;
        font-family: Verdana, Geneva, Tahoma, sans-serif;
      }
    }
    .body__wrap {
      display: flex;
      align-items: center;
      color: var(--el-text-color-regular);
      .name {
        font-size: 16px;
        font-weight: bolder;
        margin-bottom: 5px;
      }
      .phone {
        width: 100%;
        font-size: 14px;
      }
    }
    .close-icon {
      position: absolute;
      top: -5px;
      right: -5px;
      color: #7e7b7b;
      visibility: hidden;
    }
  }
  &:hover {
    .close-icon {
      visibility: visible;
    }
  }
}
.set-role {
  cursor: pointer;
  .el-card__body {
    padding: 15px !important;
  }
}
.set-role-btn {
  margin: 0px;
  margin-left: 10px;
  padding: 0px;
  font-size: 15px;
  color: #606266;
  [class*="el-icon"] + span {
    margin-left: 3px;
  }
}
.move-y {
  transition: transform 0.3s;
  &:hover {
    transform: translateY(-5px);
  }
}
</style>
